package cn.bluedot.tea.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.http.HttpSession;

import org.apache.poi.util.StringUtil;

import cn.bluedot.framework.annotations.Dispatcher;
import cn.bluedot.framework.annotations.RequestView;
import cn.bluedot.framework.annotations.ResponseJson;
import cn.bluedot.framework.annotations.Service;
import cn.bluedot.framework.service.BaseService;
import cn.bluedot.framework.util.StringUtils;
import cn.bluedot.framework.util.WebContext;
import cn.bluedot.framework.web.Result;
import cn.bluedot.tea.dao.BaseDao;
import cn.bluedot.tea.pojo.domain.Menu;
import cn.bluedot.tea.pojo.domain.ThawApplication;
import cn.bluedot.tea.pojo.domain.User;
import cn.bluedot.tea.util.DateUtil;
import cn.bluedot.tea.util.Mail;
import cn.bluedot.tea.util.MailUtils;
import cn.bluedot.tea.util.Page;
import cn.bluedot.tea.util.PageBean;

@Service //注释这是一个service，必须
public class UserService extends BaseService{ //继承超类BaseService，必须

	public UserService(){} //无参构造函数，需要
	
	public UserService(String uri, Map<String, Object[]> params, Map<String, Object> data) {
		super(params, data); //调用父类有参构造，必须
		execute(uri, params, data); //执行业务，调用父类方法
	}
	
	@RequestView(uri="/getCode")
	@ResponseJson
	private void getCode(Map<String, Object[]> params, Map<String, Object> data) throws Exception{
		Map<String, Object> param = getParameterMap(params); //将数组值转为单个值
		String email = (String) param.get("email");
	
		//验证邮箱是否存在
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("view", "selectUserCountByEmail");
		temp.put("email", email);
		
		int query = (int) BaseDao.excuteQuery(temp, null);
		if(query == 0) {
			data.put("message", email+"，用户不存在");
			data.put("Result", Result.FAILED);
			return;
		}

		Mail mail = new Mail();
		mail.setFrom("878006658@qq.com");
		mail.addTo(email);
		mail.setSubject("验证提醒");
		String code = String.valueOf(new Random().nextInt(899999) + 100000);  //得到6位验证码
		String content = "请将验证码填写到页面。如非本人操作，请忽略！<br/><br/>验证码："+code;
		mail.setContent(content);

		Session session = MailUtils.getSession("smtp.qq.com", "878006658@qq.com", "xgybupegcmrdbecj");

		try {
			MailUtils.send(session, mail);
			data.put("Result", Result.SUCCESS);
			data.put("code", code);
		} catch (MessagingException | IOException e ) {
			data.put("Result", Result.FAILED);
			data.put("message", "发送验证码失败");
			e.printStackTrace();
		}
		
		System.out.println(email+":"+code);
		
	}
	
	/**
	 * 退出登录
	 * @param params
	 * @param data
	 */
	@RequestView(uri="/logout")
	private void logout(Map<String, Object[]> params, Map<String, Object> data) {
		data.put("TYPE",Result.LOGOUT);  		
	} 

	/**
	 * 用户登录
	 * @param params 前端传入的参数值
	 * @param data  处理后返回的数据
	 * @throws Exception 
	 */
	@RequestView(uri="/login",view="login") //第一个参数为前端请求URI,第二个参数对应sql.xml里的view中的name属性
	@ResponseJson
	private void login(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
				
		Map<String, Object> param = getParameterMap(params); //将数组值转为单个值
		
		User user = (User) BaseDao.excuteQuery(param, User.class);
		
		if(user == null) {
			data.put("message", "邮箱或密码错误");
			data.put("RESULT",Result.FAILED); 
		} else {
			
			if(user.getStatus() == 0) {
				data.put("message", "当前用户被冻结，请先解冻");
				data.put("RESULT",Result.FAILED);
				return;
			}
			
			user.setPassword(null);
			data.put("user", user);
			data.put("TYPE",Result.LOGIN); 
			data.put("RESULT",Result.SUCCESS); 
		}
	}
	
	@SuppressWarnings("unchecked")
	public static HashSet<String> getMenuSet(int roleId) throws Exception {
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("view", "getMenuTreeByRole");
		param.put("roleId", roleId);
		List<Menu> menuList = (List<Menu>) BaseDao.excuteQuery(param, Menu.class, true);
		if(menuList == null) {
			return null;
		}
		HashSet<String> set = new HashSet<String>();
		for (Menu menu : menuList) {
			set.add(menu.getUrl());
		}
		return set;
	}

	/**
	 * 用户注册
	 * @param register 注册边界类
	 * @return  返回注册状态，成功返回true，失败返回false
	 * @throws Exception 
	 */
	@RequestView(uri="/register",view="register")
	@ResponseJson
	private void register(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		Map<String, Object> param = getParameterMap(params);
		//验证邮箱是否存在
		Object email = param.get("email");
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("view", "selectUserCountByEmail");
		temp.put("email", email);
		
		int query = (int) BaseDao.excuteQuery(temp, null);
		if(query > 0) {
			data.put("message", email+"已被注册,您可通过找回密码找回账号");
			data.put("RESULT", Result.FAILED);
			return;
		}
		
		//查询当前年份注册用户数量
		temp.clear();
		temp.put("view", "selectUserCountById");
		temp.put("like", "2019%");
		
		int	size = (int) BaseDao.excuteQuery(temp, null);
		
		String number = String.format("%04d", (size+1));
		//查询当前年份有多少员工
		Calendar rightNow = Calendar.getInstance();
		int year = rightNow.get(Calendar.YEAR);
		
		param.put("userId", year+number);
		param.put("roleId", 4); //默认工作人员
		param.put("status", 1); //设置为启用
		param.put("head","/assets/head/profile.jpg"); //设置为默认，后期可修改
		
		int excute = BaseDao.excute(param);
		
		if(excute > 0) {
			data.put("message", email+"注册成功,分配工号："+year+number);
			data.put("RESULT", Result.SUCCESS);
		} else {
			data.put("message", "注册失败");
			data.put("RESULT", Result.FAILED);
		}
	}
	
	@RequestView(uri="/get/user")
	@ResponseJson
	private void getUser(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		
		Map<String, Object> param = getParameterMap(params);
		
		Object email = param.get("email");
		Object id = param.get("userId");
				
		if(StringUtils.isNotEmpty(email)) {
			System.out.println("根据邮箱查询");
			param.put("view", "getUserByEmail");
		}else if(StringUtils.isNotEmpty(id)) {
			System.out.println("根据ID查询");
			param.put("view", "getUserById");
		}
		
		User user = (User) BaseDao.excuteQuery(param, User.class);
		
		if(user == null) {
			data.put("message", "当前用户不存在"); 
			data.put("RESULT", Result.FAILED);
		} else {
			user.setPassword("");
			data.put("user", user);
			data.put("RESULT", Result.SUCCESS);
		}
	}
	
	@RequestView(uri="/system/user/list", view="getUserWithRole")
	@Dispatcher(success="/system/user/user", failed="/error")
	private void getUserWithRole(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		String num = (String) param.get("pagenum");
		param.remove("pagenum");
		int pagenum = num == null ? 1 : Integer.parseInt(num);
		
		Page.startPage(pagenum, 10);
		
		List<?> query = (List<?>) BaseDao.excuteQuery(param, null);
		
		PageBean<?> pageBean = new PageBean<>(query, 10);
		data.put("query", pageBean);
		data.put("RESULT", Result.SUCCESS);
	}
	
	@RequestView(uri="/system/user/search", view="getUserSearch")
	@Dispatcher(success="/system/user/user", failed="/error")
	private void getUserSearch(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		String num = (String) param.get("pagenum");
		param.remove("pagenum");
		
		param.put("name", "%"+param.get("name")+"%"); //...
		
		int pagenum = num == null ? 1 : Integer.parseInt(num);
		
		Page.startPage(pagenum, 10);
		
		List<?> query = (List<?>) BaseDao.excuteQuery(param, null);
		
		PageBean<?> pageBean = new PageBean<>(query, 10);
		
		data.put("query", pageBean);
		data.put("RESULT", Result.SUCCESS);
		
	}
	
	@RequestView(uri="/system/thaw/list", view="getThawList")
	@Dispatcher(success="/system/thaw", failed="/error")
	private void getThawList(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		String num = (String) param.get("pagenum");
		param.remove("pagenum");
		int pagenum = num == null ? 1 : Integer.parseInt(num);
		
		Page.startPage(pagenum, 10);
		
		List<?> query = (List<?>) BaseDao.excuteQuery(param, null);
		
		PageBean<?> pageBean = new PageBean<>(query, 10);
		
		data.put("query", pageBean);
		data.put("RESULT", Result.SUCCESS);
		
	}
	
	@RequestView(uri="/system/thaw/search", view="getThawSearch")
	@Dispatcher(success="/system/thaw", failed="/error")
	private void getThawSearch(Map<String, Object[]> params, Map<String, Object> data) throws Exception  {
		Map<String, Object> param = getParameterMap(params);
		
		String num = (String) param.get("pagenum");
		param.remove("pagenum");
		int pagenum = num == null ? 1 : Integer.parseInt(num);
		
		Page.startPage(pagenum, 10);
		
		List<?> query = (List<?>) BaseDao.excuteQuery(param, null);
		
		PageBean<?> pageBean = new PageBean<>(query, 10);
		
		data.put("query", pageBean);
		data.put("RESULT", Result.SUCCESS);
		
	}
		
	@RequestView(uri="/system/user/detial",view="getUserWithRoleById")
	@Dispatcher(success="/system/user/userdetial", failed="/error")
	private void getUserDetial(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		Map<String, Object> param = getParameterMap(params);
		@SuppressWarnings("unchecked")
		List<Map> user = (List<Map>) BaseDao.excuteQuery(param, null);
		if(user == null) {
			data.put("message", "当前用户不存在"); 
		} else {
			user.get(0).put("password", "");
			data.put("user", user.get(0));
			data.put("RESULT", Result.SUCCESS);
		}
	}

	/**
	 * 找回密码
	 * @param params 找回密码边界类
	 * @param data 找回密码状态，成功返回true，失败返回false
	 * @throws Exception 
	 */
	@RequestView(uri="/alter",view="alterPassword")
	@ResponseJson
	private void alterPassword(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		Map<String, Object> param = getParameterMap(params);
		//验证邮箱是否存在
		Object email = param.get("email");
		Map<String, Object> temp = new HashMap<String, Object>();
		temp.put("view", "selectUserCountByEmail");
		temp.put("email", email);
		
		int query = (int) BaseDao.excuteQuery(temp, null);
		if(query == 0) {
			data.put("message", email+"，用户不存在");
			data.put("RESULT", Result.FAILED);
			return;
		}
		
		int excute = BaseDao.excute(param);
		
		if(excute > 0) {
			data.put("message", "修改成功");
			data.put("RESULT", Result.SUCCESS);
		} else {
			data.put("message", "修改失败");
			data.put("RESULT", Result.FAILED);
		}
	}

	/**
	 * 更新个人信息
	 * @param params 用户PO实体类
	 * @param data 更新信息状态，成功返回true,失败返回false
	 * @throws Exception 
	 */
	@RequestView(uri="/user/edit",view="userEdit")
	@ResponseJson
	private void updateUser(Map<String, Object[]> params, Map<String, Object> data) throws Exception{
		Map<String, Object> param = getParameterMap(params);
		
		int excute = BaseDao.excute(param);
		
		if(excute > 0) {
			data.put("message", "修改成功");
		}else {
			data.put("message", "修改失败");
		}
	}
	
	/**
	 * 更新用户状态
	 * @param params
	 * @param data
	 * @throws Exception
	 */
	@RequestView(uri="/update/user/status",view="updateUserStatus")
	@ResponseJson
	private void updateUserStatus(Map<String, Object[]> params, Map<String, Object> data) throws Exception{
		Map<String, Object> param = getParameterMap(params);
		int excute = BaseDao.excute(param);
		if(excute > 0 ) {
			data.put("message", "处理成功");
		}else {
			data.put("message", "处理失败");
		}
	}
	
	/**
	 * 修改密码
	 * @param params repassword 修改密码边界类
	 * @param data 修改密码状态，成功返回true，失败返回false
	 * @throws Exception 
	 */
	@RequestView(uri="/user/retpwd",view="resetPassword")
	@ResponseJson
	private void retrivePassword(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		
		Map<String, Object> param = getParameterMap(params);
		
		String id = (String) param.get("userId");
		String pwd = (String) param.get("repwd"); 
		Map<String, Object> temp = new HashMap<String, Object>();
				
		temp.put("userId", id);
		temp.put("view", "getUserById");		
				
		User query = (User)BaseDao.excuteQuery(temp, User.class);
		
		if(!query.getPassword().equals(pwd)) {
			data.put("message", "原密码错误");
			return;
		}
		param.remove("repwd");
		int excute = BaseDao.excute(param);
		
		if(excute > 0) {
			data.put("message", "修改成功");
		}else {
			data.put("message", "修改失败");
		}		
	}
		
	/**
	 *  添加单个解冻申请
	 * @param params 解冻申请边界类对象
	 * @param data 处理结果（成功，失败）
	 * @throws Exception 
	 */
	@RequestView(uri="/insert/thaw/application",view="insertThawApplication")
	@ResponseJson
	private void insertThawApplication(Map<String, Object[]> params, Map<String, Object> data) throws Exception {
		Map<String, Object> param = getParameterMap(params);
		
		param.put("applicationTime", DateUtil.getDateTime());
		param.put("status", 0);
		int excute = BaseDao.excute(param);
		if(excute > 0 ) {
			data.put("message", "解冻申请成功");
		}else {
			data.put("message", "解冻申请失败");
		}
	}

	/**
	 * 更新单个解冻申请
	 * @param params
	 * @param data
	 * @throws Exception
	 */
	@RequestView(uri="/update/thaw/application",view="updateThawApplication")
	@ResponseJson
	private void updateThawApplication(Map<String, Object[]> params, Map<String, Object> data) throws Exception{
		Map<String, Object> param = getParameterMap(params);
		param.put("checkTime", DateUtil.getDateTime());
		int excute = BaseDao.excute(param);
		if(excute > 0 ) {
			//可做后续处理（如：邮件通知之类）
			
			//修改用户状态（思考中...）
			
			data.put("message", "处理成功");
		}else {
			data.put("message", "处理失败");
		}
	}
	
	
}
